package com.cqut.familiarity.controller;


import com.cqut.familiarity.entity.Answer;
import com.cqut.familiarity.entity.vo.answerVO.AnswerVO;
import com.cqut.familiarity.entity.vo.formVO.CompletedFormVO;
import com.cqut.familiarity.entity.vo.formVO.FormVO;
import com.cqut.familiarity.entity.vo.formVO.IncompletelyFormVO;
import com.cqut.familiarity.entity.vo.questionVO.CompletedQuestionVO;
import com.cqut.familiarity.entity.vo.questionVO.IncompletelyQuestionVO;
import com.cqut.familiarity.entity.vo.questionnaireVO.CompletedQuestionaireVO;
import com.cqut.familiarity.entity.vo.questionnaireVO.IncompletelyQuestionnaireVO;
import com.cqut.familiarity.service.QuestionnaireService;
import com.cqut.familiarity.service.ScoreService;
import com.cqut.familiarity.service.UserService;
import com.cqut.familiarity.utils.ResultEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author atao
 * @since 2021-05-23
 */

@Api(description = "问卷模板信息管理")
@CrossOrigin
@RestController
@RequestMapping("/questionnaire")
public class QuestionnaireController {


    @Autowired
    private ScoreService scoreService;

    @Autowired
    private UserService userService;


    @Autowired
    private QuestionnaireService questionnaireService;



    /**
     * 根据问卷标题分页查询所有未填问卷
     * @param async
     * @param pageIndex
     * @param pageSize
     * @param title
     * @param id
     * @return
     */
    @ApiOperation(value = "根据问卷标题分页查询所有未填问卷")
    @GetMapping("/can/fill/{id}")
    public ResultEntity incompletelyPageByTitle(
            @ApiParam(name = "async", value = "是否异步请求", required = false)
            @RequestParam(value = "async",required = false,defaultValue = "true") boolean async,
            @ApiParam(name = "pageIndex", value = "当前页码", required = false)
            @RequestParam(value = "pageIndex",required = false,defaultValue = "0") int pageIndex,
            @ApiParam(name = "pageSize", value = "每页记录条数", required = false)
            @RequestParam(value = "pageSize",required = false,defaultValue = "5") int pageSize,
            @ApiParam(name = "title", value = "根据标题模糊查询", required = false)
            @RequestParam(value = "title",required = false,defaultValue = "") String title,
            @ApiParam(name = "id", value = "用户ID", required = false)
            @PathVariable("id") String id
    ){
        List<IncompletelyQuestionnaireVO> list = questionnaireService.incompletelyPageByTitle(pageIndex,pageSize,title,id);
        return ResultEntity.ok().data("list",list);
    }


    /**
     * 根据问卷标题分页查询所有已填问卷
     * @param async
     * @param pageIndex
     * @param pageSize
     * @param title
     * @param id
     * @return
     */
    @ApiOperation(value = "根据问卷标题分页查询所有已填问卷")
    @GetMapping("/completed/fill/{id}")
    public ResultEntity completedPageByTitle(
            @ApiParam(name = "async", value = "是否异步请求", required = false)
            @RequestParam(value = "async",required = false,defaultValue = "true") boolean async,
            @ApiParam(name = "pageIndex", value = "当前页码", required = false)
            @RequestParam(value = "pageIndex",required = false,defaultValue = "0") int pageIndex,
            @ApiParam(name = "pageSize", value = "每页记录条数", required = false)
            @RequestParam(value = "pageSize",required = false,defaultValue = "5") int pageSize,
            @ApiParam(name = "title", value = "根据标题模糊查询", required = false)
            @RequestParam(value = "title",required = false,defaultValue = "") String title,
            @ApiParam(name = "id", value = "用户ID", required = false)
            @PathVariable("id") String id
    ){
        List<CompletedQuestionaireVO> list = questionnaireService.completedPageByTitle(pageIndex,pageSize,title,id);
        return ResultEntity.ok().data("list",list);
    }



    /**
     * 获取问卷的详情信息
     * @param user1Id
     * @param user2Id
     * @param questionnaireId
     * @return
     */
    @ApiOperation(value = "获取问卷的详情信息")
    @PostMapping("/get/details/{user1Id}/{user2Id}/{questionnaireId}")
    public ResultEntity checkShareQuestionnaire(
            @ApiParam(name = "user1Id", value = "邀请者ID", required = true)
            @PathVariable("user1Id")String user1Id,
            @ApiParam(name = "user2Id", value = "被邀请者ID", required = true)
            @PathVariable("user2Id")String user2Id,
            @ApiParam(name = "questionnaireId", value = "问卷ID", required = true)
            @PathVariable("questionnaireId")String questionnaireId
    ){
        // 已经填写的问卷的详情
        System.out.println(questionnaireService.isFill(user1Id,user2Id,questionnaireId));
        // 已经填写
        if (questionnaireService.isFill(user1Id,user2Id,questionnaireId) != null ){
            // 完成的问题
            CompletedQuestionaireVO completedQuestionaireVO = questionnaireService.completedById(user1Id,user2Id,questionnaireId);
            // 完成的详情
            List<CompletedQuestionVO> completedQuestionVOS = questionnaireService.getDetailsOfCompelted(user1Id,user2Id,questionnaireId);
            System.out.println(completedQuestionaireVO);
            for (CompletedQuestionVO completedQuestionVO : completedQuestionVOS){
                System.out.println(completedQuestionVO);
                if (completedQuestionVO.getOptions() != null){
                    completedQuestionVO.optionsToList();
                }else {
                    break;
                }
                for (int i=0; i< completedQuestionVO.getListOptions().size(); i++){
                    if (i == Integer.valueOf(completedQuestionVO.getAnswer())){
                        completedQuestionVO.setAnswer(completedQuestionVO.getListOptions().get(i));
                        break;
                    }
                }
            }
            CompletedFormVO completedFormVO = new CompletedFormVO(completedQuestionaireVO,completedQuestionVOS);
            return ResultEntity.ok().data("form",completedFormVO);
        }else {
            IncompletelyQuestionnaireVO incompletelyQuestionnaireVO = questionnaireService.incompletelyById(user1Id,user2Id,questionnaireId);
            List<IncompletelyQuestionVO> incompletelyQuestionVOS = questionnaireService.getDetailsOfIncompletely(questionnaireId);
            for (IncompletelyQuestionVO incompletelyQuestionVO : incompletelyQuestionVOS){
                if (incompletelyQuestionVO.getOptions() != null){
                    incompletelyQuestionVO.optionsToList();
                }else {
                    break;
                }
            }
            IncompletelyFormVO incompletelyFormVO = new IncompletelyFormVO(incompletelyQuestionnaireVO,incompletelyQuestionVOS);
            return ResultEntity.ok().data("form",incompletelyFormVO);
        }
    }




    /**
     * 保存填写的问卷信息
     * @param formVO
     * @return
     */
    @ApiOperation(value = "保存填写的问卷信息")
    @PostMapping(value = "/save")
    public ResultEntity saveForm(
            @ApiParam(name = "formVO", value = "用户填写的问卷信息", required = true)
            @RequestBody FormVO formVO
    ){
        // 提取表单中的填写者id和所属者id以及问卷id
        String user1Id = formVO.getUser1Id();
        String user2Id = formVO.getUser2Id();
        String questionnaireId = formVO.getQuestionnaireId();

        // 保存用户填写的问卷信息
        for (AnswerVO answerVO: formVO.getAnswerVOList()){
            Answer answer = new Answer(answerVO);
            answer.setQuestionnaireId(questionnaireId);
            answer.setUser1Id(user1Id);
            answer.setUser2Id(user2Id);
            questionnaireService.saveAnswer(answer);
        }

        // 计算相似度
        if (user1Id.equals(user2Id)){
            List<String> userId = userService.getOthers(user1Id,questionnaireId);
            List<CompletedQuestionVO> list1 = questionnaireService.getDetailsOfCompelted(user1Id,user1Id,questionnaireId);
            for (String id : userId){
                // 对比用户自己填写的该问卷选项来计算其相似度，并将结果保存
                List<CompletedQuestionVO> list2 = questionnaireService.getDetailsOfCompelted(user1Id,id,questionnaireId);
                if (list1.size() > 0 && list2.size() > 0){
                    double res = 0;
                    if (formVO.getType().equals("0")){
                        res = scoreService.similarity(list1,list2);
                    }else {
                        res = scoreService.similarity2(list1,list2);
                    }
                    BigDecimal b = new BigDecimal(res);
                    res = b.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();
                    questionnaireService.saveResult(user1Id,id,questionnaireId,res);
                }
            }
        }else {
            // 对比用户自己填写的该问卷选项来计算其相似度，并将结果保存
            List<CompletedQuestionVO> list1 = questionnaireService.getDetailsOfCompelted(user1Id,user1Id,questionnaireId);
            List<CompletedQuestionVO> list2 = questionnaireService.getDetailsOfCompelted(user1Id,user2Id,questionnaireId);
            if (list1.size() > 0 && list2.size() > 0){
                double res = 0;
                if (formVO.getType().equals("0")){
                    res = scoreService.similarity(list1,list2);
                }else {
                    res = scoreService.similarity2(list1,list2);
                }
                BigDecimal b = new BigDecimal(res);
                res = b.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();
                questionnaireService.saveResult(user1Id,user2Id,questionnaireId,res);
            }
        }
        return ResultEntity.ok();
    }


//    /**
//     * 保存填写的问卷信息
//     * @param formVO
//     * @return
//     */
//    @ApiOperation(value = "保存填写的问卷信息(墨迹测验)")
//    @PostMapping(value = "/save2")
//    public ResultEntity saveForm2(
//            @ApiParam(name = "formVO", value = "用户填写的问卷信息", required = true)
//            @RequestBody FormVO formVO
//    ){
//        // 提取表单中的填写者id和所属者id以及问卷id
//        String user1Id = formVO.getUser1Id();
//        String user2Id = formVO.getUser2Id();
//        String questionnaireId = formVO.getQuestionnaireId();
//
//        // 保存用户填写的问卷信息
//        for (AnswerVO answerVO: formVO.getAnswerVOList()){
//            Answer answer = new Answer(answerVO);
//            answer.setQuestionnaireId(questionnaireId);
//            answer.setUser1Id(user1Id);
//            answer.setUser2Id(user2Id);
//            questionnaireService.saveAnswer(answer);
//        }
//
//        // 计算相似度
//        if (user1Id.equals(user2Id)){
//            List<String> userId = userService.getOthers(user1Id,questionnaireId);
//            List<CompletedQuestionVO> list1 = questionnaireService.getDetailsOfCompelted(user1Id,user1Id,questionnaireId);
//            for (String id : userId){
//                // 对比用户自己填写的该问卷选项来计算其相似度，并将结果保存
//                List<CompletedQuestionVO> list2 = questionnaireService.getDetailsOfCompelted(user1Id,id,questionnaireId);
//                if (list1.size() > 0 && list2.size() > 0){
//                    double res = scoreService.similarity2(list1,list2);
//                    System.out.println(res);
//                    BigDecimal b = new BigDecimal(res);
//                    res = b.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();
//                    questionnaireService.saveResult(user1Id,id,questionnaireId,res);
//                }
//            }
//        }else {
//            // 对比用户自己填写的该问卷选项来计算其相似度，并将结果保存
//            List<CompletedQuestionVO> list1 = questionnaireService.getDetailsOfCompelted(user1Id,user1Id,questionnaireId);
//            List<CompletedQuestionVO> list2 = questionnaireService.getDetailsOfCompelted(user1Id,user2Id,questionnaireId);
//            if (list1.size() > 0 && list2.size() > 0){
//                double res = scoreService.similarity2(list1,list2);
//                System.out.println(res);
//                BigDecimal b = new BigDecimal(res);
//                res = b.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();
//                questionnaireService.saveResult(user1Id,user2Id,questionnaireId,res);
//            }
//        }
//        return ResultEntity.ok();
//    }


}

